<?php
namespace weixin\mp;

require_once "helper.php";

class access_token {
    private $app_id;
    private $app_secret;

    /**
     * AccessToken构造器
     * @param [Number] $agentId 两种情况：1是传入字符串“txl”表示获取通讯录应用的Secret；2是传入应用的agentId
     */
    public function __construct() {
        $config = load_config();
        $this -> app_id = $config -> app_id;
        $this -> app_secret = $config -> app_secret;
    }

    public function get_access_token() {

        //TODO: access_token 应该全局存储与更新，以下代码以写入到文件中做示例
        //NOTE: 由于实际使用过程中不同的应用会产生不同的token，所以示例按照agentId做为文件名进行存储

        $path = TEMP_PATH . "mp.php";
        $data = json_decode(get_php_file($path));
        if ($data -> expire_time < time()) {

            $urlj = $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this -> app_id . '&secret=' . $this -> app_secret;
            $ret = http_get($url);
            $ret = $ret['content'];
            $ret = json_decode($ret, true);

            $access_token = $ret['access_token'];

            if ($access_token) {
                $data -> expire_time = time() + 7000;
                $data -> access_token = $access_token;
                set_php_file($path, json_encode($data));
            }
        } else {
            $access_token = $data -> access_token;
        }
        return $access_token;
    }

}
